package com.sky.service.impl;


import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    AddressBookMapper addressBookMapper;

    /**
     * 添加地址
     * @param addressBook
     */
    @Override
    public void add(AddressBook addressBook) {
        // 用当前线程设置地址簿的user_id
        addressBook.setUserId(BaseContext.getCurrentId());
        // 设置地址是否为默认地址
        addressBook.setIsDefault(0);
        addressBookMapper.add(addressBook);
    }

    /**
     * 查询当前用户所有地址
     * @return
     */
    @Override
    public List<AddressBook> list() {
        // 创建地址簿对象
        AddressBook addressBook = new AddressBook();
        // 根据当前线程(用户)指定地址簿user_id
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> addressBookList = addressBookMapper.list(addressBook);
        return addressBookList;
    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public AddressBook getDefault() {
        // 创建地址簿对象
        AddressBook addressBook = new AddressBook();
        // 根据当前线程(用户)指定地址簿user_id
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(1);
        addressBook = addressBookMapper.getDefault(addressBook);
        return addressBook;
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    @Override
    public void setDefault(AddressBook addressBook) {

        // 设置地址为非默认
        addressBook.setIsDefault(0);
        // 修改当前用户的所有地址为非默认
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateIsDefaultByUserId(addressBook);

        // 设置地址为默认
        addressBook.setIsDefault(1);
        // 持久层
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id修改地址
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        // 持久层
        addressBookMapper.update(addressBook);

    }

    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }
}
